/// 时间转换类
class Date {
  /// 现在的时间 自定义格式
  static String now({String format = 'y-m-d h:i:s'}) {
    DateTime dateTime = DateTime.now();
    return timestamp(dateTime.millisecondsSinceEpoch, format: format);
  }

  /// 时间戳转换为自定义格式的时间
  static String timestamp(int stamp, {String format = 'y-m-d h:i:s'}) {
    DateTime dateTime = timestampToDatetime(stamp);

    if (dateTime == null) {
      return "";
    }

    Map<String, String> dateList = {
      "y": dateTime.year.toString().padLeft(2, '0'),
      "m": dateTime.month.toString().padLeft(2, '0'),
      "d": dateTime.day.toString().padLeft(2, '0'),
      "h": dateTime.hour.toString().padLeft(2, '0'),
      "i": dateTime.minute.toString().padLeft(2, '0'),
      "s": dateTime.second.toString().padLeft(2, '0'),
    };

    dateList.forEach((k, v) {
      format = format.replaceAll(k, v);
    });

    return format;
  }

  /// 时间戳转换为自定义格式的时间，但是根据距离当前的时间长度不同，表现有所不同
  /// 今天内的显示为 09:20
  /// 昨天的时间显示为 昨天09:20
  /// 昨天之前的显示为 2019-01-23 09:20
  static String simple(int stamp, {String format = 'y-m-d h:i:s'}) {
    DateTime dateTime = timestampToDatetime(stamp);

    if (dateTime == null) {
      return "";
    }

    DateTime today = DateTime.now();
    DateTime standardDate = DateTime(today.year, today.month, today.day, 23, 59, 59);

    Duration diff = standardDate.difference(dateTime);

    String hour = dateTime.hour.toString().padLeft(2, '0');
    String minute = dateTime.minute.toString().padLeft(2, '0');

    if (diff < Duration(days: 1)) {
      return "$hour:$minute";
    } else if (diff >= Duration(days: 1) && diff < Duration(days: 2)) {
      return "昨天 $hour:$minute";
    } else {
      return timestamp(stamp, format: format);
    }
  }

  /// 时间戳转换为DateTime
  static DateTime timestampToDatetime(int stamp) {
    bool result = [10, 13].contains("$stamp".length);
    if (!result) {
      print("Date报错：时间戳格式不正确");
      return null;
    }

    if ("$stamp".length == 10) {
      stamp = stamp * 1000;
    }

    return DateTime.fromMillisecondsSinceEpoch(stamp);
  }

  /// 计算时间差
  /// 默认为 h:i:s
  static String difference(int startStamp, int endStamp, {String format = 'h:i:s'}) {
    DateTime startDateTime = timestampToDatetime(startStamp);
    DateTime endDateTime = timestampToDatetime(endStamp);

    if (startDateTime == null || endDateTime == null) {
      return null;
    }

    Duration difference = endDateTime.difference(startDateTime);

    // 求余 补0
    String hours = (difference.inHours % 24).toString().padLeft(2, '0');
    String minutes = (difference.inMinutes % 60).toString().padLeft(2, '0');
    String seconds = (difference.inSeconds % 60).toString().padLeft(2, '0');

    Map<String, String> dateList = {
      "h": hours,
      "i": minutes,
      "s": seconds,
    };

    dateList.forEach((k, v) {
      format = format.replaceAll(k, v);
    });

    return format;
  }
}
